import React, { Component,PropTypes } from 'react';
import {Link} from 'react-router';
import Footer from '../../Component/CommonComponent/Footer';
import ItemDetails from '../../Component/OrderManage/ItemDetails';
import CheckBox from '../../Component/OrderManage/CheckBox';
import IsShowEmptyImg from '../CommonComponent/IsShowEmptyImg'
import {AddPayOrder,EditShopNum,DelShopCar,SettlementPurchase,MyInfo,AgentProductList} from '../../Action/auth'
import '../../Stylesheets/wx/shoppingCarts.css';
import DelayModal from '../../Component/CommonComponent/DelayModal'
import $ from 'jquery';

export default class Purchase extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        //是否使用全选按钮
        this.isUseSelectAll = false;
        this.amount = 0;
        this.select = [];
        this.selectNum = [];
        this.selectDel = [];
        this.selectStock = [];
        this.showDetail = [];
        this.click=true;
        this.firstCom = true;
        this.state = {
            selectAll:false,
            toRender:1,
            amount : 0 ,
            index : 0,
            goodsList:[],
            isActive:'',
            grade:0,
            nowAmount:0,
            useAmount:0,
            needPay:0,
            modalDelay:false,
            display:'block',
            items: [],
            loadMore:false,
            end:false,
            last:false,
        };
        this.page = 1;
        this.over = false;
        this.dataList=[];
        this.itemsChanged = false;
    }

    static contextTypes = {
        router:PropTypes.object
    }

    async componentWillMount() {
        await this.getMyInfo();
        if(this.state.grade>0){
            this.getAgentProductList(0,1,'')
        }
    }

    //获取个人信息
    async getMyInfo(){
        await MyInfo()
            .then(res=>{
                this.setState({isActive:res.IS_ACTIVE})
                this.setState({grade:res.AGENT_GRADE})
                this.setState({nowAmount:res.NOW_AMOUNT})
                this.setState({useAmount:res.USE_AMOUNT})
                this.setState({needPay:res.TOTAL_APY*0.9})
            })
    }

    //进货列表
    async getAgentProductList(status,page,name){
        if(this.over){
            return
        }
        this.setState({display:'block',loadMore:true})
        await AgentProductList(status,page,name)
            .then(res=>{
                this.setState({loadMore:false});
                if(this.page==Math.ceil(res.total/res.pageSize)){
                    this.over=true;
                }else{
                    this.over=false;
                }
                this.dataList = this.dataList.concat(res.resultList);
                this.setState({goodsList:this.dataList});
                this.page++;
            })
            .catch(err=>{
                console.warn('err',err)
            })
    }

    end(){
        let h = Math.floor(parseFloat($('#scrollWrap').height()));
        let wrapH = Math.ceil(parseFloat($('#listWrap').height()));
        if( (h - wrapH-5)<=$('#listWrap').scrollTop() ){
            if(this.over){
                this.setState({loadMore:false,end:true});
            }else{
                this.setState({loadMore:true});
                this.getAgentProductList(0,1,'')
            }
        }
    }


    //全选/反选
    async onChangeState(){
        this.isUseSelectAll = true;
        this.setState({selectAll:!this.state.checked});
        if(this.select.length<this.state.goodsList.length){
            this.select = [];
            await this.setState({selectAll:true});
            this.state.goodsList.map(el=>{
                this.select.push(el.ID);
                this.selectNum[el.ID]=$('#'+el.ID).val();
            })
        }else{
            this.setState({selectAll:false});
            this.select = [];
        }

        this.countAmount();
        this.setState({toRender:1});
        console.log('selected',this.select);
    }

    //单选
    getSelect(state,id){
        this.isUseSelectAll = false
        console.log('state',state)
        if(state){
            this.select.push(id);
            this.selectNum[id]=$('#'+id).val();
        }else{
            this.select = this.select.filter(el=>{
                if(el==id){
                    return false
                }
                return true
            })
        }
        this.countAmount()
        this.setState({toRender:1})
    }

    async editShopNum(id){
        if($('#'+id).val()>0){
            this.selectNum[id]=$('#'+id).val();
            this.countAmount()
        }else{
            $('#'+id).val(1)
        }
    }

    //计算总价
    countAmount() {
        this.selectStock=[];
        this.showDetail = [];
        this.state.goodsList.map(el=>{
            let num = this.selectNum[el.ID]?this.selectNum[el.ID]:0
            this.select.map(item=>{
                if(el.ID == item){
                    console.log(this.selectNum[item])
                    this.amount += el.price*(this.selectNum[item])
                    this.selectStock.push({productId:el.ID,num:this.selectNum[item]})
                    this.showDetail.push({num:this.selectNum[item],productName:el.NAME})
                }
            })
        })
        this.setState({amount:this.amount})
        this.amount = 0
    }


    async toSubmit(){
        if(this.click){
            this.click = false;
            if(this.select.length>0){
                const nowAmount = this.state.nowAmount;
                const useAmount = this.state.useAmount;
                const total = this.state.amount;

                //判断是否为首次进货与是否满足首次进货条件
                if(this.state.grade>0 && this.state.isActive ==1){
                    //取掉90%的限制
                    /*if(total<this.state.needPay){
                        alert('首次进货需进最低'+this.state.needPay+'元的货物')
                        this.click = true;
                        this.firstCom = false;
                        return
                    }
                    else{
                        this.firstCom = true;
                    }*/
                }

                if(this.firstCom){
                    let detailString = "";
                    this.showDetail.map(item=>{
                        detailString += " " + item.productName;
                        detailString += (",数量" + item.num +  "件"+ "\n");
                    })
                    if(confirm("确认进货"+"\n" + detailString)){
                        if(nowAmount+useAmount>=total){
                            await this.setState({modalDelay:true})
                            await SettlementPurchase(JSON.stringify(this.selectStock))
                                .then(res=>{
                                    this.ToGetOrder(res.orderNo,res.amount/100)
                                })
                                .catch(err=>{
                                    alert(err.message)
                                    this.click = true;
                                    this.setState({modalDelay:false})
                                    console.warn('err',err)
                                })
                        }else{
                            alert('您的货款不足，请充值');
                            this.context.router.push({pathname:'/recharge',query:{purchase:2}})
                            this.click = true;
                        }
                    }else{
                        this.click = true;
                        return;
                    }

                }
            }else{
                alert('请选择商品')
                this.click = true;
            }
        }

    }

    ToGetOrder(orderNo,amount){
        AddPayOrder(orderNo,2,'',amount,2)
            .then(res=>{
                alert('进货成功，请等待发货')
                this.click = true;
                this.context.router.push({pathname:'/personalCenter',query:{orderId:res}})
                this.setState({modalDelay:false})
            })
            .catch(err=>{
                console.warn('获取资料失败',err)
                this.click = true;
            })
    }



    render() {
        const {goodsList,amount,scrollTop, loadMore,end,last} = this.state
        return (
            <div>
                <div className="containerNav bkg_color" style={{bottom:50}}>
                    <div id="listWrap"
                         onTouchEnd={()=>this.end()}
                         style={{position:'absolute',top:0,left:0,right:0,bottom:0,overflowX:'auto'}}>
                        <div id="scrollWrap">
                        {
                            goodsList&&goodsList.map((el,index)=>{
                                let num = 'num'+index;
                                return(
                                    <div className="padd10 border_bottom flex flex-align-center" style={{height:120}}>
                                        <CheckBox
                                            selectAll = {this.isUseSelectAll?this.state.selectAll:null}
                                            index={index}
                                            onSelect = {(state)=>this.getSelect(state,el.ID)}
                                        />
                                        <div className="f12 flex-1 homePage">
                                            <div className="di imgPlay fl mr">
                                                <img src={el.IMAGE} alt=""/>
                                            </div>
                                            <div>
                                                <span className="productShow db">{el.NAME}</span>
                                                <span className="color9">{el.DESC}</span>
                                            </div>
                                            <div>
                                                <span className="colorff f12">￥</span><span className="colorff f16">{el.price}</span>
                                            </div>
                                            <div className="flex f14">
                                                进货：
                                                <div className="di border_4 cartCount tc flex" style={{border:'none'}}>
                                                    <input
                                                        id={el.ID}
                                                        type="number"
                                                        style={{width:80,borderBottom:'1px solid #e5e5e5'}}
                                                        className="di height100 borderno tc widthChange"
                                                        onBlur={()=>this.editShopNum(el.ID)}
                                                        placeholder="请输入"
                                                        defaultValue="1"
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                        {/*  <ItemDetails
                                         price={el.price}
                                         title={el.NAME}
                                         attr={el.DESC}
                                         imgurl={el.IMAGE}
                                         num={this.number}
                                         changeNum ={(value,type)=>this.editShopNum(el.ID,value,type)}
                                         />*/}
                                    </div>
                                )
                            })
                        }
                        {
                            loadMore?
                                <div className="tc mt f12 colorfa">
                                    加载更多
                                </div>
                                :null

                        }
                        {
                            end?
                                <div  className="tc mt f12 colorfa" style={{paddingBottom:10}}>
                                    没有更多数据了哦
                                </div>
                                :null
                        }
                            {/*   <p ref="PullUp" id='pullUp' className="flip"
                           style={{display:this.state.display}}
                        ><div className="pullUpIcon"></div>上拉显示更多...</p>*/}
                    </div>
                    </div>
                </div>
                    <div className="pf bottomCount flex flex-align-center flex-pack-justify plr width100" style={{bottom:0}}>
                        <div className="flex flex-align-center">
                            <span className="di check_radius posr fl">
                                <input
                                    type="checkbox" id="checkAll"
                                    checked={this.select.length&&(this.select.length==this.state.goodsList.length)?true:false}
                                    onClick={()=>this.onChangeState()}
                                    className="di isCheck"
                                />
                                <label htmlFor="checkAll"></label>
                            </span>
                            <span className="di f14 color6 ml height100 lh25">全选</span>
                            <div className="di ml flex flex-v">
                                <div>
                                    <label className="f12">合计</label>
                                    <span className="colorlv f12">￥</span><span className="colorlv f18">{amount}</span>
                                </div>
                            </div>
                        </div>
                        <button
                            onClick={()=>this.toSubmit()}
                            className="settleAccount border_4 colorfff borderno"
                        >
                            结算
                        </button>
                    </div>
                {
                    this.state.modalDelay?
                        <DelayModal />
                        :null

                }
            </div>
        );
    }
}
